﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Data;

namespace WxPayAPI
{
    public partial class DownloadBillPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Log.Debug(this.GetType().ToString(), "page load");
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(bill_date.Text))
            {
                Response.Write("<script LANGUAGE='javascript'>alert('请输入对账单日期！');</script>");
                return;
            }

            //调用下载对账单接口,如果内部出现异常则在页面上显示异常原因
            try
            {
                string result = DownloadBill.Run(bill_date.Text, bill_type.SelectedValue);

                StrToDataTable(result);


                Response.Write("<span style='color:#00CD00;font-size:20px'>" + result + "</span>");
            }
            catch (WxPayException ex)
            {
                Response.Write("<span style='color:#FF0000;font-size:20px'>" + ex.ToString() + "</span>");
            }
            catch (Exception ex)
            {
                Response.Write("<span style='color:#FF0000;font-size:20px'>" + ex.ToString() + "</span>");
            }
        }


        private DataTable StrToDataTable(string str)
        {
            Regex regex = new Regex("\r\n");
            string[] lows = regex.Split(str);

            DataTable dt = new DataTable();

            string[] str_colNames = lows[0].Split(',');
            for (int i = 0; i < str_colNames.Length; i++)
            {
                dt.Columns.Add(str_colNames[i], typeof(string));
            }

            for (int i = 1; i < lows.Length - 2; i++)
            {
                DataRow dr=dt.NewRow();
                string[] str_values = lows[i].Split(',');
                for (int j = 0; j < str_values.Length; j++)
                {
                    dr[j]=str_values[j];
                }
                dt.Rows.Add(dr);
            }

            return dt;

        
        }
    }
}